package org.sbbs.app.security.service.impl;

import java.util.HashSet;
import java.util.List;

import org.sbbs.app.security.dao.RoleDao;
import org.sbbs.app.security.dao.UserDao;
import org.sbbs.app.security.model.Role;
import org.sbbs.app.security.model.User;
import org.sbbs.app.security.service.UserManager;
import org.sbbs.base.service.impl.BaseManagerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("userManager")
public class UserManagerImpl extends BaseManagerImpl<User, Long>
		implements
			UserManager,
			UserDetailsService {
	private UserDao userDao;
	private RoleDao roleDao;
	private PasswordEncoder passwordEncoder;

	@Autowired
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	@Autowired
	public UserManagerImpl(UserDao userDao) {
		super(userDao);
		this.userDao = userDao;
	}

	public RoleDao getRoleDao() {
		return roleDao;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User ud = this.userDao.loadUserByUsername(username);
		List<Role> roles = this.roleDao.getRolesByUserId(((User) ud).getId());
		ud.setRoles(new HashSet(roles));
		return ud;
	}
}
